package com.webserver.core;

import javax.naming.ldap.SortKey;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 负责与指定客户端进行一次HTTP交互
 * HTTP协议要求客户端与服务端采取一问一答的交互规则.
 * 并在交互完毕后断开TCP连接
 *
 * 因此,这里处理一次HTTP交互采取的过程分为三部分:
 * 1:解析请求(读取客户端发送过来的HTTP请求内容)
 * 2:处理请求(分析请求信息确定客户端意图,并进行对应的处理)
 * 3:发送响应(给浏览器发送一个HTTP中的响应,将处理结果回复给浏览器)
 */
public class ClientHandler implements Runnable{
    private Socket socket;

    public ClientHandler(Socket socket){
        this.socket=socket;
    }

    public void run() {
        try {
//1.1解析请求行
            String line=readLine();
            System.out.print("请求行内容:"+line);
            String method;
            String uri;
            String protocol;
            String[] data= line.split("\\s");
            method=data[0];
            uri=data[1];
            protocol=data[2];

            System.out.println("method"+method);
            System.out.println("uri"+uri);
            System.out.println("protocol"+protocol);
//1.2解析消息头
            Map<String,String> headers=new HashMap<>();
            while (true) {
                line = readLine();
                if (line.isEmpty()){
                    break;
                }
                System.out.println("消息头:" + line);
                data=line.split("\\s");
                headers.put(data[0],data[1]);
            }
            System.out.println("headers:"+headers);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //交互后与客户端断开连接(协议要求)
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    private String readLine() throws IOException {
        InputStream in=socket.getInputStream();
        int d;
        StringBuilder builder=new StringBuilder();
        char cur='a',pre='a';
        while ((d=in.read())!=-1){
            cur=(char)d;
            if (pre==13&&cur==10){
                break;
            }
            builder.append(cur);
            pre=cur;

        }
        return builder.toString().trim();
    }
}
